import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    UserOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const items: MenuItem[] = [
  getItem('page1', '/', <PieChartOutlined />),
  getItem('page2', '/page2', <DesktopOutlined />),
  getItem('User', '/user', <UserOutlined />),
  getItem('page3', 'page3', <FileOutlined />,
    [
      getItem('page301', '/page3'),
      getItem('Bill', '4'),
      getItem('Alex', '5'),
    ]
  )
];

const Comp: React.FC = () => {
    const navigateTo = useNavigate()
    const currerRouter = useLocation() // 获取当前路径
    
    // 点击左侧菜单栏
    const menuClick = (e:{key: string}) => {
        //console.log(e.key);
        navigateTo(e.key)
    }

    function findKey(item: MenuItem) {
      return item!.key === currerRouter.pathname
    }
    // 第一次打开时的openKey
    let firstOpenKey: string = ''
    for(let i = 0; i< items.length; i++){
      if(items[i]!['children'] && items[i]!['children'].find(findKey)){
        firstOpenKey = items[i]!.key
        break
      }
    }
    
    const [openKeys, setOpenKeys] = useState([firstOpenKey]);
    const handleOnpenChange = (keys: string[]) => {
        //console.log(keys);
        setOpenKeys([keys[keys.length-1]])
    }
    return (
        <Menu
         theme="dark"
          defaultSelectedKeys={[currerRouter.pathname]}
          mode="inline"
          items={items}
          onClick={menuClick}
          onOpenChange={handleOnpenChange}
          openKeys={openKeys}
        />
    )
}
export default Comp;